package com.smartsofa.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.util.LineView;
import com.smartsofa.util.MyUtils;

public class HistoryActivity extends Activity {
//	int randomint = 10;
//    Random rand=new Random();
    private ListView lv_history ;
    private Button bt_his_xueya;
    private Button bt_his_xueyang;
    private Button bt_his_xuetang;
    private LineView lineView;
    private int green;
    private int darkgray;
    
    private String url;
    private Boolean flag=false;
	Intent intent;
	private int styleMode=1;
	private List<Map<String,Object>> list;
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	private JSONObject json;
	private Button bt_his_back;
@Override
protected void onCreate(Bundle savedInstanceState) {	
	
	super.onCreate(savedInstanceState);	
	setContentView(R.layout.activity_history);
	lineView = (LineView)findViewById(R.id.line_view);
	
	//back
	bt_his_back=(Button) findViewById(R.id.bt_his_back);
	bt_his_back.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			HistoryActivity.this.finish();
		}
	});
	
    //must*
    ArrayList<String> test = new ArrayList<String>();
    for (int i=0; i<10; i++){
        test.add(String.valueOf(i+1));
    }
    lineView.setBottomTextList(test);
    lineView.setDrawDotLine(true);
    lineView.setShowPopup(LineView.SHOW_POPUPS_NONE);

    ArrayList<Float> dataList1= new ArrayList<Float>();
	ArrayList<Float> dataList2= new ArrayList<Float>();
	ArrayList<ArrayList<Float>> dataLists= new ArrayList<ArrayList<Float>>();
	for (int i=0; i<10; i++){
        dataList1.add((float) (i*2+3));
    }
	for (int i=0; i<10; i++){
        dataList2.add((float) (i*2+3));
    }
	dataLists.add(dataList1);
	dataLists.add(dataList1);
	lineView.setDataLists(dataLists);
	 list =new ArrayList<Map<String,Object>>();
//    lv_history = (ListView) findViewById(R.id.lv_history);
    bt_his_xueya = (Button) findViewById(R.id.bt_his_xueya);
    bt_his_xueyang = (Button) findViewById(R.id.bt_his_xueyang);
    bt_his_xuetang = (Button) findViewById(R.id.bt_his_xuetang);
    
    green=getResources().getColor(R.color.reddeep);
    darkgray=getResources().getColor(R.color.darkgray);
    
    Thread thread =new Thread(new LoadDataThread());
    thread.start();	
    final boolean netstate=MyUtils.isNetworkConnected(getApplicationContext());
    if(!netstate){
		Toast.makeText(HistoryActivity.this,"网络无法连接，请检查你的网络！",Toast.LENGTH_SHORT).show();
	}
    bt_his_xueya.setOnClickListener( new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if(!netstate){
				Toast.makeText(HistoryActivity.this,"网络无法连接，请检查你的网络！",Toast.LENGTH_SHORT).show();
			}
			bt_his_xueya.setBackgroundColor(green);
			bt_his_xueyang.setBackgroundColor(darkgray);
			bt_his_xuetang.setBackgroundColor(darkgray);
			styleMode=1;		
			 Thread thread =new Thread(new LoadDataThread());
			    thread.start();	
		}
	});
    bt_his_xuetang.setOnClickListener( new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			if(!netstate){
				Toast.makeText(HistoryActivity.this,"网络无法连接，请检查你的网络！",Toast.LENGTH_SHORT).show();
			}
			bt_his_xueya.setBackgroundColor(darkgray);
			bt_his_xueyang.setBackgroundColor(darkgray);
			bt_his_xuetang.setBackgroundColor(green);
			styleMode=2;
			 Thread thread =new Thread(new LoadDataThread());
			    thread.start();	
		}
	});
    bt_his_xueyang.setOnClickListener( new OnClickListener() {
	
    	@Override
		public void onClick(View v) {
    		if(!netstate){
				Toast.makeText(HistoryActivity.this,"网络无法连接，请检查你的网络！",Toast.LENGTH_SHORT).show();
			}
    		bt_his_xueya.setBackgroundColor(darkgray);
			bt_his_xueyang.setBackgroundColor(green);
			bt_his_xuetang.setBackgroundColor(darkgray);
			styleMode=3;	
			 Thread thread =new Thread(new LoadDataThread());
			    thread.start();	
	}
});
}



class LoadDataThread implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {			
			int dataType=1;
			switch(styleMode){
				case 1: dataType=1;break;
				case 2: dataType=3;break;
				case 3: dataType=4;break;
			}
			url=MyUtils.getUrl()+"display_historylist?userid="+MyUtils.getUSERID()+"&datatype="+dataType+"&currpage=1&pagesize=360";
			HttpGet request = new HttpGet(url);																
			BasicHttpParams httpParams = new BasicHttpParams();
		    HttpConnectionParams.setConnectionTimeout(httpParams,3000);
	        HttpClient httpClient = new DefaultHttpClient(httpParams);
	        HttpResponse httpResponse = httpClient.execute(request);						       
	       	
	      if (httpResponse.getStatusLine().getStatusCode() == 200) {
	    	network_timeout=true;  
	        String jsonString = EntityUtils.toString(httpResponse.getEntity());
	        json = new JSONObject(jsonString);
	        flag=(Boolean) json.get("success");       
	        }
	      }catch (Exception e) {
	        	 e.printStackTrace();
	      }
		Message msg = content_handler.obtainMessage();
		if (flag) {				
			msg.what = 1;							
		}
		else if(!flag){
			msg.what = 2;	
		}
		else{
			msg.what = 3;
		}
		content_handler.sendMessage(msg);
}		
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {		
			case 1:
				try {
					ArrayList<String> timeData= new ArrayList<String>();
					ArrayList<Float> dataList1= new ArrayList<Float>();
					ArrayList<Float> dataList2= new ArrayList<Float>();
					ArrayList<ArrayList<Float>> dataLists= new ArrayList<ArrayList<Float>>();

					if(network_timeout){
					    if(flag == true){
					        switch(styleMode){
					        case 1:
					        	JSONArray jsonarr1;
								
								dataList1.clear();
								dataList2.clear();
								dataLists.clear();
								list.clear();
								JSONObject jsonobj = new JSONObject();
								JSONArray jsonarr2;
								
								jsonobj=json.getJSONObject("obj");
								jsonarr1 = jsonobj.getJSONArray("SBP");
								jsonarr2 = jsonobj.getJSONArray("DBP");

								String date;
								float soushuoya;
								float shuzhangya;
	
								for(int i=jsonarr1.length()-1;i>=0;i--){
									date=jsonarr1.getJSONObject(i).getString("uploadTime").substring(5, 10);
									soushuoya=(float) jsonarr1.getJSONObject(i).getDouble("dataValue");
									shuzhangya=(float) jsonarr2.getJSONObject(i).getDouble("dataValue");
									timeData.add(date);
									dataList1.add(soushuoya);
									dataList2.add(shuzhangya);
								}							
								
								dataLists.add(dataList1);
								dataLists.add(dataList2);
								lineView.setStyleMode(1);
								lineView.setBottomTextList(timeData);
								lineView.setDataLists(dataLists);							        	
					        		        	
					        	break;
					        case 2:
					        	try {
									dataList1.clear();
									dataList2.clear();
									dataLists.clear();
									list.clear();
									jsonarr1=json.getJSONArray("obj"); 
									System.out.println("jsonarr1.length()-"+jsonarr1.length());
									String date1;
									float xuetang;
									
									for(int i=jsonarr1.length()-1;i>=0;i--){
										date1=jsonarr1.getJSONObject(i).getString("uploadTime").substring(5, 10);
										xuetang=(float) jsonarr1.getJSONObject(i).getDouble("dataValue");
										timeData.add(date1);
										dataList1.add(xuetang);

									}	

									dataLists.add(dataList1);
									dataLists.add(dataList2);
									
									lineView.setStyleMode(2);
									lineView.setBottomTextList(timeData);
									lineView.setDataLists(dataLists);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}	        	
					        	
					        	
					        	break;
					        case 3:
					        	dataList1.clear();
					        	dataList2.clear();
					        	dataLists.clear();
					        	jsonarr1= json.getJSONArray("obj");   
					        	Log.i("xueyang json",jsonarr1.toString());
					   
					        	for(int i=jsonarr1.length()-1;i>=0;i--){
					        		timeData.add(jsonarr1.getJSONObject(i).getString("uploadTime").substring(5, 10));
					        		dataList1.add((float) jsonarr1.getJSONObject(i).getDouble("dataValue"));
					        		dataList2.add((float) 0);
					        		
					        	}
					        	Log.i("datalist1", dataList1.get(0).toString());
					        	
					        	dataLists.add(dataList1);
					        	dataLists.add(dataList2);
					        	lineView.setStyleMode(3);
					        	lineView.setBottomTextList(timeData);
					        	lineView.setDataLists(dataLists);	        	
					        	
					        	
					        	
					        }
					        }
					        else{
					        	
					        	ArrayList<String> test = new ArrayList<String>();
					            for (int i=0; i<10; i++){
					                test.add(String.valueOf(i+1));
					            }
					            lineView.setBottomTextList(test);
					            lineView.setDrawDotLine(true);
					            lineView.setShowPopup(LineView.SHOW_POPUPS_NONE);
					            lineView.setDrawDataLineState(false);
					            
					        	
					        	for (int i=0; i<10; i++){
					                dataList1.add((float) (i*2+3));
					            }
					        	for (int i=0; i<10; i++){
					                dataList2.add((float) (i*2+3));
					            }
					        	dataLists.add(dataList1);
					        	dataLists.add(dataList1);
					        	lineView.setDataLists(dataLists);
					        	Log.i("else", "i am already in else");

					        }	       	       	     
					      }
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 2:
				Toast.makeText(getApplicationContext(), "您还未测试，暂时无历史数据，请稍后再试！", Toast.LENGTH_LONG).show();
				break;
			case 3:
				Toast.makeText(getApplicationContext(), "网络连接超时！", Toast.LENGTH_LONG).show();
				break;
			}
		}
	};
	}	
	
}



